import React, { memo, useEffect, useState, useCallback } from "react";
import { Select } from "antd";
import PropTypes from "prop-types";

import { custom } from "services/common";
interface PropsKey {
  label: string;
  value: string;
}
interface Props {
  url?: string;
  selectOptions?: any[]; //上面两个二选一
  propsKey: PropsKey; //这玩意必须要传 代表显示什么拿到什么值
  style?: object;
  placeholder?: string;
  [propName: string]: any;
}
const { Option } = Select;
const SelectComp = function (props: Props) {
  // state
  const { style, selectOptions, propsKey, placeholder, url, value } = props;
  const [optionAry, setOptionAry] = useState(selectOptions);
  const [values, setValue] = useState();

  const getData = useCallback(
    async (url: string) => {
      const res: any = await custom({ url });
      if (res.data && res.data.data.length > 0) {
        setOptionAry(res.data.data);
      }
    },
    [setOptionAry]
  );
  useEffect(() => {
    if (url) {
      getData(url);
    }
  }, [getData,url]);
  //   生命周期
  useEffect(() => {
    if (!isNaN(value) && value && optionAry && optionAry.length > 0) {
      const data: any =
        optionAry &&
        optionAry.filter((item: any) => +item[propsKey.value] === +value)[0];
      const name = data && data[propsKey.label];
      setValue(name);
    }
  }, [value, url, propsKey, optionAry]);

  // 其它逻辑

  const onCurrencyChange = (val: string) => {
    if (Number.isNaN(parseInt(val))) return;
    // value和onChange都是From.item传递下来的 --类似双向绑定的原理
    props.onChange(parseInt(val));
  };
  return (
    <Select
      style={style}
      placeholder={placeholder}
      onChange={onCurrencyChange}
      value={values}
    >
      {optionAry &&
        optionAry.map((elem: any) => {
          //  -这里怕名字重复 用索引key={index}
          return (
            <Option value={elem[propsKey?.value]} key={elem[propsKey?.label]}>
              {elem[propsKey?.label]}
            </Option>
          );
        })}
    </Select>
  );
};

// 校验数据类型
SelectComp.propTypes = {
  SelectComp: PropTypes.string, //必须要的 要么就和options二选一
  options: PropTypes.array,
  propsKey: PropTypes.object, //里面的数据结构是 value label   propsKey:{label:'name',value:'id'} 用来获取值 配合url一起使用
  style: PropTypes.object,
  placeholder: PropTypes.string,
};
// 默认
SelectComp.defaultProps = {
  options: [],
  style: {},
  url: "",
  placeholder: "请选择",
};

export default memo(SelectComp);
